import { useMemo, useState } from 'react';
import type { SelectProps } from './index';

export function transValueToSelectedValue(value: any, multiple: boolean, joinValues: boolean, delimiter: string) {
  let list: any[] = [];
  if (value || typeof value === 'number') {
    if (multiple) {
      if (joinValues) {
        if (typeof value !== 'string') {
          console.warn('transValueToSelectedValue 数据解析异常 非string', arguments);
        } else {
          list = value.split(delimiter);
        }
      } else {
        if (!Array.isArray(value)) {
          console.warn('transValueToSelectedValue 数据解析异常 非array', arguments);
        } else {
          list = value.concat();
        }
      }
    } else {
      if (typeof value !== 'string' && typeof value !== 'number') {
        console.warn('transValueToSelectedValue 数据解析异常2 非string和number', arguments);
      } else {
        list = [value];
      }
    }
  }
  return list;
}

export function transSelectedValueToValue(selectedValue: any[], multiple: boolean, joinValues: boolean, delimiter: string) {
  // console.log('transSelectedValueToValue', { selectedValue, multiple, joinValues, delimiter });
  let value: any;
  if (selectedValue.length) {
    if (multiple) {
      if (joinValues) {
        value = selectedValue.join(delimiter);
      } else {
        value = selectedValue;
      }
    } else {
      value = selectedValue[0];
    }
  } else {
    if (multiple) {
      value = joinValues ? '' : [];
    } else {
      value = '';
    }
  }
  // console.log('transSelectedValueToValue', { value });
  return value;
}

/**
 * 转化value为Index列表
 * @param value 一维数组 [1,1,1] or '1,1,1'
 * @param optionList 二维数组 [{value:xxx},{value:xxx}]
 * @returns
 */
export function transValueToSelectedIndexes(
  value: any,
  optionList: any[][],
  multiple: boolean,
  joinValues: boolean,
  delimiter: string,
  valueField: string,
): number[] {
  const selectedValue = transValueToSelectedValue(value, multiple, joinValues, delimiter);
  if (!optionList?.length || !selectedValue.length) return [];
  const selectedIndexes = optionList.map((options, index) => {
    return options.findIndex(option => option[valueField] === selectedValue[index]);
  });
  return selectedIndexes;
}

export function getSelectedItemsByOptions(options: any[], list: any[], valueField: string) {
  let selectedItem: any[] = [];
  if (options.length && list.length) {
    list.forEach(item => {
      const option = options.find(option => option[valueField] === item);
      if (option) {
        selectedItem.push(option);
      }
    });
  }
  return selectedItem;
}

interface I_TreeItem {
  children?: I_TreeItem[];
  /** 当前层次如：第三层第二个 0-0-1 */
  _indexs?: string;
  [key: string]: any;
}

function flattenTree(tree: I_TreeItem[], withIndexs = false) {
  const flatList: I_TreeItem[] = [];
  function trans(list: I_TreeItem[], parentIndexs: string, parent?: I_TreeItem) {
    list.forEach((v, i) => {
      flatList.push(v);
      const _indexs = parentIndexs ? parentIndexs + '-' + i : String(i);
      if (withIndexs) {
        v._indexs = _indexs;
        if (parent) v._parent = parent;
      }
      if (v.children?.length) {
        trans(v.children, _indexs, v);
      }
    });
  }
  trans(tree, '');
  return flatList;
}

export function findItemsInTree(keys: any[], tree: I_TreeItem[], fn: (item: I_TreeItem) => boolean) {
  if (!keys.length) return [];
  const list = flattenTree(tree);
  const items: any[] = keys.map(item => {
    return fn(item);
  });
  console.log('findItemsInTree', list, items);
  return items;
}

/** 抹平树为一维数组 */
export const useFlattenOptions = (tree: I_TreeItem[]) => {
  const flattenOptions = useMemo(() => {
    if (tree?.length) {
      return flattenTree(tree, true);
    }
    return [];
  }, [tree]);
  // console.log('useFlattenOptions', flattenOptions);
  return flattenOptions;
};

/** 根据搜索词过滤options */
export const useFilterOptions = (
  searchable: boolean,
  searchStr: string,
  options: SelectProps['options'],
  flattenOptions: SelectProps['options'],
  labelField: string,
) => {
  const list = useMemo(() => {
    if (!searchStr) {
      return options;
    }
    const matchList: I_TreeItem[] = []; // 全部匹配的item
    const matchIndexs: string[] = []; // [ '1','1-1'] 不重复
    flattenOptions!.filter(v => {
      if (v[labelField].toLowerCase().includes(searchStr.toLowerCase())) {
        let pre = '';
        v._indexs!.split('-').forEach(i => {
          pre = !pre ? i : pre + '-' + i.toString();
          const indexStr = pre;
          if (!matchIndexs.includes(indexStr)) {
            matchIndexs.push(indexStr);
            matchList.push(flattenOptions!.find(v => v._indexs === indexStr)!);
          }
        });
      }
    });
    // console.log('matchIndexs', matchIndexs, matchList);

    function listToTree(list1: Array<{ _indexs: string; [key: string]: any }>): I_TreeItem[] {
      const treeMap: { [key: string]: I_TreeItem } = {};

      // 将原始列表转换为键值对映射表（父节点 -> 子节点）
      list1.forEach(item => {
        const levels = item._indexs.split('-');
        let currentLevelNode: I_TreeItem | undefined = treeMap[levels[0]];
        if (!currentLevelNode) {
          currentLevelNode = { ...item, _indexs: item._indexs };
          treeMap[levels[0]] = currentLevelNode;
        }

        for (let i = 1; i < levels.length; i++) {
          const nextLevelIndex = levels[i];
          let nextLevelNode: I_TreeItem | undefined = currentLevelNode?.children?.find(
            child => child._indexs === `${currentLevelNode._indexs}-${nextLevelIndex}`,
          );
          if (!nextLevelNode) {
            nextLevelNode = { ...item, _indexs: `${currentLevelNode._indexs}-${nextLevelIndex}` };
            if (!currentLevelNode.children) {
              currentLevelNode.children = [];
            }
            currentLevelNode.children.push(nextLevelNode);
          }
          currentLevelNode = nextLevelNode;
        }
      });

      // 从映射表中提取根节点
      return Object.values(treeMap).filter(node => !node._indexs.includes('-'));
    }

    return listToTree(matchList);
  }, [searchStr, options, flattenOptions, labelField]);
  // console.log('useFilterOptions', searchStr, list);
  return list;
};

export const useExpandKeys = () => {
  const [expandKeys, setExpandKeys] = useState<any[]>([]);

  const toggleExpandItem = key => {
    if (expandKeys.includes(key)) {
      setExpandKeys(expandKeys.filter(item => item !== key));
    } else {
      setExpandKeys([...expandKeys, key]);
    }
  };
  return {
    expandKeys,
    setExpandKeys,
    toggleExpandItem,
  };
};

/** 返回祖先+自己的items */
export const getAncestorAndCurrent = (item: any) => {
  if (!item) return [];
  let list: (typeof item)[] = [];
  while (item) {
    list.push(item);
    item = item._parent;
  }
  list.reverse();
  return list;
};
